﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using SoonCode.Core;
using SoonCode.FocusTest.Api;
using SoonCode.FocusTest.Events;
using SoonCode.FocusTest.Models;
using SoonCode.FocusTest.Utils;
using MessageBox = HandyControl.Controls.MessageBox;

namespace SoonCode.FocusTest.ViewModels
{
    internal class SubmitViewModel:BindableBase
    {
        private int TestItemIndex = 9;
        private ObservableCollection<TestInfoExt> testInfo;
        private IEventAggregator aggregator;
        private string[] itemNames = ["听觉广度", "听觉记忆", "听觉加工", "听觉稳定", "视觉分辨", "视觉广度", "视觉记忆", "手部控制", "视觉加工"];
        private bool isSubmit = false;
        private bool isNotSubmit=false;
        private Dictionary<string, string> testResult;
        private string pid;
        private bool isLoading = false;
        private bool canSubmit = true;

        public bool CanSubmit
        {
            get
            {
                return canSubmit;
            }
            set
            {
                canSubmit=value;
                RaisePropertyChanged();
            }
        }

        public bool IsLoading
        {
            get { return isLoading; }
            set
            {
                isLoading=value;
                CanSubmit = !IsLoading;
                RaisePropertyChanged();
            }
        }
        public bool IsNotSubmit
        {
            get { return isNotSubmit; }
            set
            {
                isNotSubmit=value;
                RaisePropertyChanged();
            }
        }

        public bool IsSubmit
        {
            get { return isSubmit; }
            set
            {
                isSubmit=value;
                IsNotSubmit=!value;
                RaisePropertyChanged();
            }
        }
        public ObservableCollection<TestInfoExt> TestInfo
        {
            get { return testInfo; }
            set
            {
                testInfo = value;
                RaisePropertyChanged();
            }
        }

        public ICommand SubmitDataCommand { get; set; }
        public ICommand PrintCommand { get; set; }
        public ICommand ExitCommand { get; set; }
        public SubmitViewModel(IEventAggregator aggregator)
        {
            this.aggregator = aggregator;
            this.SubmitDataCommand = new DelegateCommand(SubmitHandler);
            this.PrintCommand = new DelegateCommand(PrintHandler);
            this.ExitCommand = new DelegateCommand(ExitCommandHandler);
            aggregator.GetEvent<TestLoadEvent>().Subscribe(OnLoaded);
        }

        private void ExitCommandHandler()
        {
            aggregator.GetEvent<EndTestEvent>().Publish();
        }
        private void PrintHandler()
        {
            TestPrintModel model = new TestPrintModel();
            MemberInfo member = GlobalModel.Instance.MemberInfo;
            model.Age = member.showAge;
            model.Name=member.name;
            model.Sex=member.sex;
            model.AvgScore = testResult["averageScore"];
            model.PID = pid;
            model.TestDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            for (int i = 1; i <= 9; i++)
            {
                string[] val = testResult["score" + i].Split(":");
                model.ScoreList.Add(new ScoreModel() { Name = val[0], Score = val[1] });
            }
            EventInfo info=new EventInfo();
            info.Type = TestPrintModel.type;
            info.Data["model"]=model;
            this.aggregator.GetEvent<PrintTestResultEvent>().Publish(info);
        }

        private async void SubmitHandler()
        {
            try
            {
                TestInfo testInfo = GlobalModel.Instance.TestInfo;
                Guid guid = Guid.NewGuid();
                testInfo.pid = guid.ToString().Replace("-", "").ToUpper();
                pid = testInfo.pid;
                IsLoading = true;
                testResult = await API.SubmitTest(testInfo);
                GlobalModel.Instance.OrgInfo = await API.GetCurrOrg();
                OrgInfo orginfo = GlobalModel.Instance.OrgInfo;
                if (orginfo.serviceType == "frequency"&&orginfo.testNumber<=5)
                {
                    MessageBox.Show($"您的评测次数还剩余{orginfo.testNumber}", "系统提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                }

                if (testResult == null) return;
                for (int i = 1; i <= 9; i++)
                {
                    string[] val = testResult["score" + i].Split(":");
                    TestInfo[i - 1].score_value = val[1];
                }

                IsSubmit = true;
                this.aggregator.GetEvent<SubmitTestResultEvent>().Publish();
            }
            catch (Exception e)
            {
                DialogUtil.Show(aggregator, "错误：" + e.Message);
            }
            finally
            {
                IsLoading = false;
            }
        }
        private void OnLoaded(int p)
        {
            if (p != this.TestItemIndex - 1)
            {
                return;
            }
            IsSubmit=false;
            Task.Run(getData);

        }

        private void getData()
        {
            this.TestInfo = new ObservableCollection<TestInfoExt>();
            foreach (TestData data in GlobalModel.Instance.TestInfo.data)
            {
                TestInfoExt testInfo = new TestInfoExt();
                testInfo.item_no = data.item_no;
                testInfo.item_score=data.item_score;
                testInfo.score_value= testInfo.item_score == "-1" ? "未测试完成" : "已测试完成";
                testInfo.item_name = itemNames[testInfo.item_no.ToInt() - 1];
                TestInfo.Add(testInfo);
            }
        }
    }
    
    public class TestInfoExt : BindableBase
    {
        public string item_no { get; set; }
        public string item_score { get; set; }
        public string item_name { get; set; }
        private string _item_name;
        private string _score_value;
        public string item_color
        {
            get
            {
                return item_score == "-1" ? "Red" : "Green";
            }
        }
        public string score_value
        {
            get { return _score_value; }
            set
            {
                _score_value = value;
                RaisePropertyChanged();
            }

        }
    }
}
